﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace ConcordWinManager
{
    public partial class TemplateEditForm : Form
    {
        public Template template;

        private string mode;

        private Form parentForm;

        private bool act = false;

        public TemplateEditForm()
        {
            InitializeComponent();
        }

         /// <summary>
        /// Конструктор на добавление
        /// </summary>
        /// <param name="parentForm"></param>
        /// <param name="mode"></param>
        public TemplateEditForm(Form parentForm, string mode)
        {
            InitializeComponent();
            this.mode = mode;

            this.Text = string.Format("Шаблон [{0}]", mode);

            this.parentForm = parentForm;

            if (this.mode == "Добавление")
            {
                template = new Template();                
                act = true;
            }            
        }

         /// <summary>
        /// Конструктор на изменение
        /// </summary>
        /// <param name="parentForm"></param>
        /// <param name="mode"></param>
        /// <param name="id"></param>
        public TemplateEditForm(Form parentForm, string mode, int id)
        {
            InitializeComponent();

            this.parentForm = parentForm;

            this.Text = string.Format("Консультант [{0}]", mode);

            this.mode = mode;

            if (mode == "Изменение")
            {
                this.template = new Template();
                Tools.RunWithProgressIndicator(this, delegate
                {
                    template.SelectById(id);

                    //template.rezident = new Rezident().SelectById(template.id_rezident);                                       
                });

                tbxTemplateName.Text = template.Name;
                tbxNote.Text = template.Note;
                tbxPath.Text = template.SourceFilePath;

                foreach (Control control in this.Controls)
                {
                    if (control is RadioButton)
                    {
                        if (control.Tag.ToString() == template.DocType)
                        {
                            ((RadioButton)control).Checked = true;
                        }
                    }
                }

            }

            this.act = true;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            bool bSuccessfully = false;

            template.Name = tbxTemplateName.Text;
            template.Note = tbxNote.Text;

            foreach (Control control in this.Controls)
            {
                if (control is RadioButton)
                {
                    if (((RadioButton)control).Checked)
                    {
                        template.DocType = control.Tag.ToString();
                    }
                }
            }

            if (!(template.Name.Length > 0 &&
                template.SourceFilePath != null &&
                template.DocType != null))
            {
                MessageBox.Show("Не все обязательные для заполнения поля заполнены", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (this.mode == "Изменение")
                {
                    Tools.RunWithProgressIndicator(this, delegate { template.Update();});
                    //ВСТАВИТЬ ПРОВЕРКУ УСПЕШНОСТИ ВЫПОЛНЕНИЯ
                    MessageBox.Show("Шаблон успешно изменен", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (mode == "Добавление")
                    {
                        Tools.RunWithProgressIndicator(this, delegate { template.Insert(); });
                        //ВСТАВИТЬ ПРОВЕРКУ УСПЕШНОСТИ ВЫПОЛНЕНИЯ
                        MessageBox.Show("Шаблон успешно добавлен", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                } 

                bSuccessfully = true;
            }
            catch
            {
                MessageBox.Show("Шаблон не добавлен", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if (bSuccessfully)
            {
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Microsoft Word|*.doc; *.rtf";

            if (tbxPath.Text.Length > 0)
            {
                if(File.Exists(tbxPath.Text))
                {
                    FileInfo fi = new FileInfo(tbxPath.Text);
                    GZipHelper.Decompress(fi);
                    openFileDialog.InitialDirectory = fi.DirectoryName;                    
                }
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                FileInfo fi = new FileInfo(openFileDialog.FileName);

                tbxPath.Text = fi.FullName;
                tbxTemplateName.Text = fi.Name;

                Tools.RunWithProgressIndicator(this, delegate
                {
                    GZipHelper.Compress(fi);

                    template.Filename = fi.Name;

                    CRC32Helper crc32 = new CRC32Helper();
                    String hash = String.Empty;

                    using (FileStream fs = File.Open(fi.FullName + ".gz", FileMode.Open))
                    {
                        foreach (byte b in crc32.ComputeHash(fs))
                        {
                            hash += b.ToString("x2").ToLower();
                        }
                    }

                    template.crc32 = hash;
                    template.SourceFilePath = fi.FullName + ".gz";
                    template.Filename = fi.Name;
                });

            }
        }
                

        private void btnViewTemplate_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}
